from flask import session, redirect, url_for
from werkzeug.security import check_password_hash, generate_password_hash
from blueprints import auth_blueprint
from models import User, UpdateInstance, Personal, QueryOneInstance, Role
from tools.response import Response, ResponsePostJson


def NewUser(json):
    user = User(username=json['username'], password=generate_password_hash(json['password']))
    UpdateInstance(user)
    UpdateInstance(Personal(),{"uid":user.id})
    UpdateInstance(Role(),{"uid":user.id})


@auth_blueprint.route('/public/service/register', methods=['POST'])
def post_public_service_of_register():
    def cb(json):
        user = QueryOneInstance(User, {'username': json['username']})
        if not user:
            NewUser(json)
            return Response("注册成功")
        return Response("已存在用户")
    return ResponsePostJson(['username', 'password'], cb)

@auth_blueprint.route('/public/service/login', methods=['POST'])
def post_public_service_of_login():
    def cb(json):
        user = QueryOneInstance(User, {'username': json['username']})
        if user is None:
            return Response('用户不存在')
        if check_password_hash(user.password, json['password']):
            session['uid'] = user.id
            session['username'] = user.username
            # TODO url
            return redirect(url_for('block.get_public_page_of_blocks'))
        return Response('用户名与密码不匹配')
    return ResponsePostJson(['username', 'password'], cb)